//
//  SubmitDemandsViewController.m
//  ForestPack
//
//  Created by 骆锴 on 2018/7/23.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SubmitDemandsViewController.h"
#import "AddImgButton.h"
#import <CTAssetsPickerController/CTAssetsPickerController.h>

@interface SubmitDemandsViewController () <UITextViewDelegate,UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,CTAssetsPickerControllerDelegate>

@property (nonatomic, strong) UIScrollView      *mainView;
@property (nonatomic, strong) UITextField       *productnamevalue;
@property (nonatomic, strong) UITextField       *namevalue;
@property (nonatomic, strong) UITextField       *phonevalue;
//@property (nonatomic, strong) UITextField       *productnamevalue2;
@property (nonatomic, strong) UITextView        *demandsvalue;
@property (nonatomic, strong) UIButton          *selectYesButton;
@property (nonatomic, strong) UIButton          *selectNoButton;
@property (nonatomic, strong) NSArray           *selectedpics;
//@property (nonatomic, strong) UILabel           *numofname;
@property (nonatomic, strong) UIView            *selectPhoto;
@property (nonatomic, assign) YesOrNoType       yesOrNoType;
@property (nonatomic,strong)  UILabel           *numofpicture;


@property (nonatomic, strong) NSMutableArray    * picsImageArray;
@property (nonatomic, strong) NSMutableArray    * picsUrlArray;
@property (nonatomic, assign)  NSInteger           picsCount;
@property (nonatomic, strong)  AddImgButton      * addImageButton;

@end

@implementation SubmitDemandsViewController

- (NSMutableArray *)picsUrlArray
{
    if (_picsUrlArray == nil) {
        _picsUrlArray = [[NSMutableArray alloc] init];
    }
    return _picsUrlArray;
}

- (NSMutableArray *)picsImageArray
{
    if (_picsImageArray == nil) {
        _picsImageArray = [[NSMutableArray alloc] init];
    }
    return _picsImageArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
//    _pics = [[NSMutableArray alloc] initWithCapacity:5];
    _mainView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT)];
    _mainView.contentSize = CGSizeMake(SCREEN_WIDTH, ScreenX375(800));
    [self.view addSubview:_mainView];
    [self setUI];
//    [self setpics];
    self.yesOrNoType = YesOrNoType_Yes;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(releasefirstResponder)];
    [self.view addGestureRecognizer:tap];
    
}

- (void)setNavBar {
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 14, 44)];
    [backBtn setImage:[UIImage imageNamed:@"返回白色"] forState:UIControlStateNormal];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    [backBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    [self setTitle:@"提需求"];
}

#pragma mark - 提交需求
-(void)submitClick
{
    if (self.namevalue.text.length <= 0 || self.productnamevalue.text.length <= 0 || self.demandsvalue.text.length <= 0) {
        [HttpManager showNoteMsg:@"请填写完整"];
        return;
    }
    if (self.phonevalue.text.length != 11 ) {
        [HttpManager showNoteMsg:@"请输入正确的手机号"];
        return;
    }
    if (self.productnamevalue.text.length > 10) {
        [HttpManager showNoteMsg:@"请输入不超过十个字的商品名称"];
        return;
    }
    
    if (self.picsImageArray.count <= 0) {
        [HttpManager showNoteMsg:@"请上传不超过5张的图片"];
        return;
    }
    [HttpManager uploadImageArr:self.picsImageArray success:^(id successResponse) {
        self.picsUrlArray = successResponse;
        [self requestData];
    }];
    
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - 选择图片上传
-(void)selectPics
{
    self.picsCount = 5 - self.picsImageArray.count;
    if (self.picsCount == 0) {
        return;
    }
    [self alterIconPortrait];
}

#pragma mark - 请求数据
-(void)requestData
{
    NSString * picUrl = @""; /// [0], [1]
    for (NSString * urlStr in self.picsUrlArray) {
        if ([picUrl isEqualToString:@""]) {
            picUrl = urlStr;
        }else{
            picUrl = [NSString stringWithFormat:@"%@,%@",picUrl, urlStr];
        }
    }
    
    NSString *url = [NSString stringWithFormat:@"%@app/solution_order",REQUESTHEADER];//发布需求
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    if (self.isOrNotDirecIdType == IsOrNotDirecIdType_Yes) {
        [dict setValue:self.design_id forKey:@"design_id"];//如果是选择上个界面的某个点击进来的，需要传design_id
        [dict setValue:[FPLoginAndRegisterTools getToken] forKey:@"token"];//token
        [dict setValue:self.productnamevalue.text forKey:@"name"];//产品名称
        [dict setValue:self.demandsvalue.text forKey:@"describe"];//具体要求
        [dict setValue:self.phonevalue.text forKey:@"telephone"];//手机号码
        [dict setValue:self.namevalue.text forKey:@"user_name"];//联系姓名
        [dict setValue:@(self.yesOrNoType) forKey:@"is_kind"];//是否制样
        [dict setValue:picUrl forKey:@"pic"];//需求图（两个url之间以逗号隔开）
    }
    [dict setValue:[FPLoginAndRegisterTools getToken] forKey:@"token"];//token
    [dict setValue:self.productnamevalue.text forKey:@"name"];//产品名称
    [dict setValue:self.demandsvalue.text forKey:@"describe"];//具体要求
    [dict setValue:self.phonevalue.text forKey:@"telephone"];//手机号码
    [dict setValue:self.namevalue.text forKey:@"user_name"];//联系姓名
    [dict setValue:@(self.yesOrNoType) forKey:@"is_kind"];//是否制样
    [dict setValue:picUrl forKey:@"pic"];//需求图（两个url之间以逗号隔开）
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager showNoteMsg:@"提交成功"];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
    
}

#pragma mark----- 选择弹出框
-(void)alterIconPortrait
{
    //弹出提示框
    __weak typeof(self)weakSelf = self;
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：拍摄
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamare];
    }]];
    //按钮：从手机相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [weakSelf openAlbum];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 打开相册
-(void)openAlbum
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
        dispatch_async(dispatch_get_main_queue(), ^{

            if (status != PHAuthorizationStatusAuthorized) {
                return ;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                // init Picker弹出图片选择界面
                CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
                //隐藏空相册
                picker.showsEmptyAlbums = NO;
                //允许显示图片选中后的顺序
                picker.showsSelectionIndex = YES;
                //选择需要弹出的相册，一般我们只需要弹出相机胶卷和自定义相册即可
                picker.assetCollectionSubtypes = @[
                                                   @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                                   @(PHAssetCollectionSubtypeAlbumRegular)
                                                   ];
                // picker delegate
                picker.delegate = self;
                
                // present picker
                [self presentViewController:picker animated:YES completion:nil];
                
            });
            
        });
    }];
}

/*
#pragma mark - 设置图片最多选九张
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = 5;
    if (picker.selectedAssets.count < max) return YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:[NSString stringWithFormat:@"最多选择5张图片"] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    //一定要用picker 不能用self 因为当前显示在最上面的控制器是picker 而不是self
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    for(NSString *str in assets){
        [_pics addObject:str];
        [self setpics:_pics];
        NSLog(@"%ld",_pics.count);
        NSLog(@"%@",_pics);
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    UIImagePickerController *pickerC = [[UIImagePickerController alloc] init];
    pickerC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickerC.delegate = self;
    
    [self presentViewController:pickerC animated:YES completion:nil];
    
//    for (int i = 0; i < assets.count; i++) {
//        [_pics addObject:[assets valueForKey:@"filename"]];
//    }
//    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
//    options.resizeMode = PHImageRequestOptionsResizeModeExact;
//    options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
//
//    for (NSInteger i = 0; i < assets.count; i ++) {
//        PHAsset *asset = assets[i];
//        NSLog(@"%@",[asset valueForKey:@"filename"]);
//        CGFloat scale = UIScreen.mainScreen.scale;
//        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
//
//        //请求图片 (需要先用图片管理员请求图片数据 请求完成后 在block里添加图片)
//        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//            WeakObj(self);
//                [HttpManager uploadImage:result success:^(id successResponse) {
//                    NSLog(@"%@",successResponse);
//                    [selfWeak.pics addObject:successResponse];
//                }];
//        }];
//    }
    for (int i = 0; i < assets.count; i++) {
        PHAsset *ass = assets[i];
        // 获取所有资源的集合，并按资源的创建时间排序
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
        [assetsFetchResults enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PHAsset *ass2 = obj;
            if ([ass.localIdentifier isEqualToString:ass2.localIdentifier]) {
                [self.pics addObject:ass.localIdentifier];
            }
        }];
    }
    NSLog(@"%@",self.pics);
    [self setpics:_pics];
}

//- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
//{
//    for(NSString *str in assets){
//        [_pics addObject:str];
//        [self setpics:_pics];
//        NSLog(@"%ld",_pics.count);
//        NSLog(@"%@",_pics);
//        [picker dismissViewControllerAnimated:YES completion:nil];
//    }
//    UIImagePickerController *pickerC = [[UIImagePickerController alloc] init];
//    pickerC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    pickerC.delegate = self;
//
//    [self presentViewController:pickerC animated:YES completion:nil];
//
//}
*/

#pragma mark - 打开相机
-(void)openCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - UIImagePickerControllerDelegate  图片处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSLog(@"Picker returned successfully.");
    //将选择的图片在imageView上显示
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self.picsImageArray addObject:image];
    
    CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
    for (int i = 0; i < self.picsImageArray.count; i++) {
        
        CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
        CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(430);
        UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
        imageV.image = self.picsImageArray[i];
        [self.mainView addSubview:imageV];
    }
    [self setAddPicsUI];
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 设置图片最多选九张
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    NSInteger max = self.picsCount;
    if (picker.selectedAssets.count < max) return YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:[NSString stringWithFormat:@"最多选择%ld张图片",(long)max] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    //一定要用picker 不能用self 因为当前显示在最上面的控制器是picker 而不是self
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

#pragma mark - 选择完毕的时候调用
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    //选择图片时的配置项 (如果不写配置项 会导致请求的图片尺寸出现问题)
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    //遍历图片选择的图片显示成九宫格样式
    for (NSInteger i = 0; i < assets.count; i ++) {
        PHAsset *asset = assets[i];
        CGFloat scale = UIScreen.mainScreen.scale;
        CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
        
        //请求图片 (需要先用图片管理员请求图片数据 请求完成后 在block里添加图片)
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            WeakObj(self);
                [selfWeak.picsImageArray addObject:result];
            CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
            for (int i = 0; i < self.picsImageArray.count; i++) {

                CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
                CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(430);
                UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
                imageV.image = self.picsImageArray[i];
                [self.mainView addSubview:imageV];
            }
            [self setAddPicsUI];
            
            
        }];
        
//        [self setAddPicsUI];
    }
}

-(void)setAddPicsUI
{
    CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
    
    if (self.picsImageArray.count != 5) {
        self.addImageButton.frame = CGRectMake(self.picsImageArray.count % 3 * (ScreenX375(110) + margin) + ScreenX375(13), self.picsImageArray.count / 3 * ScreenX375(120) + ScreenX375(430), ScreenX375(110), ScreenX375(110));
        
        [self.addImageButton addTarget:self action:@selector(selectPics) forControlEvents:UIControlEventTouchUpInside];
        [self.mainView addSubview:self.addImageButton];
    }
    
    self.numofpicture.text = [[NSString stringWithFormat:@"%lu",(unsigned long)self.picsImageArray.count] stringByAppendingString:@"/5"];//@"0/5"
}

-(void)setUI
{
    NSArray *title = [[NSArray alloc] initWithObjects:@"产品名称 :", @"具体要求 :", @"联系姓名 :", @"手机号码 :", @"是否制样 :",@"上传图片 :(仅支持jpg/png格式图片)",   nil];//@"商品名称 :",
    NSArray *titleheight = [[NSArray alloc] initWithObjects:@"15",@"60",@"215",@"259",@"333",@"385",nil];//@"430",
    for (int i = 0; i < title.count; i++) {
        if (i == 5) {
            UILabel *titlelabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375([[titleheight objectAtIndex:i] integerValue]), ScreenX375(250), ScreenX375(14))];
            titlelabel.text = [title objectAtIndex:i];
            titlelabel.font = Kfont(14.0);
            titlelabel.textAlignment = NSTextAlignmentLeft;
            [_mainView addSubview:titlelabel];
        }else{
            UILabel *titlelabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375([[titleheight objectAtIndex:i] integerValue]), ScreenX375(80), ScreenX375(14))];
            titlelabel.text = [title objectAtIndex:i];
            titlelabel.font = Kfont(14.0);
            titlelabel.textAlignment = NSTextAlignmentLeft;
            [_mainView addSubview:titlelabel];
        }
    }
    
    _productnamevalue = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), ScreenX375(15), SCREEN_WIDTH-ScreenX375(99), ScreenX375(14))];
    _productnamevalue.placeholder = @"请输入不超过十个字的商品名称";
    _productnamevalue.delegate = self;
//    [_productnamevalue addTarget:self action:@selector(setNumofname) forControlEvents:UIControlEventEditingChanged];
    _productnamevalue.textAlignment = NSTextAlignmentLeft;
    _productnamevalue.font = Kfont(14.0);
    [_mainView addSubview:_productnamevalue];
    
//    _numofname = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(337), ScreenX375(17), ScreenX375(40), ScreenX375(11))];
//    _numofname.text = @"0/10";
//    _numofname.font = Kfont(12.0);
//    _numofname.textColor = REXADECIMALCOLOR(@"#999999");
//    [_mainView addSubview:_numofname];
    
    NSArray *height = [[NSArray alloc] initWithObjects:@"44",@"244",@"288",@"370", nil];//@"414",
    for (int i = 0; i < height.count; i++) {
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375([[height objectAtIndex:i] integerValue]), ScreenX375(349), ScreenX375(1))];
        UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"虚线"]];
        [line setBackgroundColor:color];
        [_mainView addSubview:line];
    }
    
    self.demandsvalue = [[UITextView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(89), ScreenX375(349), ScreenX375(112))];
    self.demandsvalue.textColor = REXADECIMALCOLOR(@"#999999");
    self.demandsvalue.text = @"请尽可能描述您的需求(包装材质、印刷工艺、尺寸、用途)";
    self.demandsvalue.delegate = self;
    self.demandsvalue.textAlignment = NSTextAlignmentLeft;
    self.demandsvalue.font = Kfont(12.0);
    self.demandsvalue.layer.cornerRadius = 6.0;
    self.demandsvalue.layer.borderWidth = 1.0;
    self.demandsvalue.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
    [_mainView addSubview:self.demandsvalue];
    
    _namevalue = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), ScreenX375(215), ScreenX375(150), ScreenX375(14))];
    _namevalue.placeholder = @"请输入您的姓名";
    _namevalue.delegate = self;
    _namevalue.textAlignment = NSTextAlignmentLeft;
    _namevalue.font = Kfont(14.0);
    [_mainView addSubview:_namevalue];
    
    _phonevalue = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), ScreenX375(259), ScreenX375(259), ScreenX375(14))];
    _phonevalue.placeholder = @"请输入您的手机号码";
    _phonevalue.delegate = self;
    _phonevalue.textAlignment = NSTextAlignmentLeft;
    _phonevalue.keyboardType = UIKeyboardTypeNumberPad;
    _phonevalue.font = Kfont(14.0);
    [_mainView addSubview:_phonevalue];
    
    UILabel *warming = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(299), ScreenX375(330), ScreenX375(11))];
    warming.textColor = ThemeColor;
    warming.text = @"确保信息正确无误,以便印前人员可以与您及时联系确认印刷需求";
    warming.font = Kfont(11);
    [_mainView addSubview:warming];
    
    self.selectYesButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(87), ScreenX375(325), ScreenX375(109), ScreenX375(30))];
    [self.selectYesButton setTitle:@"是" forState:UIControlStateNormal];
    [self.selectYesButton setTitleColor:REXADECIMALCOLOR(@"#999999") forState:UIControlStateNormal];
    [self.selectYesButton setTitleColor:ThemeColor forState:UIControlStateSelected];
    self.selectYesButton.selected = YES;
    [self.selectYesButton addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    self.selectYesButton.layer.borderColor = ThemeColor.CGColor;
    self.selectYesButton.layer.borderWidth = 0.5;
    self.selectYesButton.layer.cornerRadius = 15.0;
    [_mainView addSubview:self.selectYesButton];
    
    self.selectNoButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(206), ScreenX375(325), ScreenX375(109), ScreenX375(30))];
    [self.selectNoButton setTitle:@"否" forState:UIControlStateNormal];
    [self.selectNoButton setTitleColor:REXADECIMALCOLOR(@"#999999") forState:UIControlStateNormal];
    [self.selectNoButton setTitleColor:ThemeColor forState:UIControlStateSelected];
    self.selectNoButton.selected = NO;
    [self.selectNoButton addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    self.selectNoButton.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
    self.selectNoButton.layer.borderWidth = 0.5;
    self.selectNoButton.layer.cornerRadius = 15.0;
    [_mainView addSubview:self.selectNoButton];
    
    self.numofpicture = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(337), ScreenX375(385), ScreenX375(26), ScreenX375(11))];//432
    self.numofpicture.text = @"0/5";
    self.numofpicture.font = Kfont(12.0);
    self.numofpicture.textColor = REXADECIMALCOLOR(@"#999999");
    [_mainView addSubview:self.numofpicture];
    
//    _selectPhoto = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(430), ScreenX375(110), ScreenX375(110))];
//    _selectPhoto.userInteractionEnabled = true;
    UIImageView *border = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(110), ScreenX375(110))];
    UIButton *add =  [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(35), ScreenX375(35))];
    [add setBackgroundImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    border.image = [UIImage imageNamed:@"虚线边框"];
//    [border addSubview:add];
//    add.center = border.center;
//    [_selectPhoto addSubview:border];
//    [_mainView addSubview:_selectPhoto];
    
//    UIButton *selectPicsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    selectPicsBtn.frame = _selectPhoto.bounds;
//    [selectPicsBtn addTarget:self action:@selector(selectPics) forControlEvents:UIControlEventTouchUpInside];
//    [_selectPhoto addSubview:selectPicsBtn];
    
    self.addImageButton = [[AddImgButton alloc] init];
    self.addImageButton.frame = CGRectMake(ScreenX375(13), ScreenX375(430), ScreenX375(110), ScreenX375(110));
    [self.mainView addSubview:self.addImageButton];
    [self.addImageButton addTarget:self action:@selector(selectPics) forControlEvents:UIControlEventTouchUpInside];
    if (self.picsImageArray.count >= 5) {
        self.addImageButton.hidden = YES;
    }
//    [self setAddPicsUI];
    
    UIButton *submit = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(678), ScreenX375(349), ScreenX375(44))];
    submit.backgroundColor = ThemeColor;
    submit.layer.cornerRadius = 22.0;
    [submit setTitle:@"立即提交" forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
    [_mainView addSubview:submit];
    
}


//-(void)setAddPicsUI
//{
//    CGFloat margin = (SCREEN_WIDTH - ScreenX375(26) - ScreenX375(330)) / 2;
////    for (int i = 0; i < self.picsImageArray.count; i++) {
////
////        CGFloat x = i % 3 * (ScreenX375(110) + margin) + ScreenX375(13);
////        CGFloat y = i / 3 * ScreenX375(120) + ScreenX375(430);
////        UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, ScreenX375(110), ScreenX375(110))];
////        imageV.image = self.picsImageArray[i];
////        [self.mainView addSubview:imageV];
////    }
//
//
//    if (self.picsImageArray.count != 5) {
//        self.addImageButton = [[AddImgButton alloc] initWithFrame:CGRectMake(self.picsImageArray.count % 3 * (ScreenX375(110) + margin) + ScreenX375(13), self.picsImageArray.count / 3 * ScreenX375(120) + ScreenX375(430), ScreenX375(110), ScreenX375(110))];
//
//        [self.addImageButton addTarget:self action:@selector(selectPics) forControlEvents:UIControlEventTouchUpInside];
//        [self.mainView addSubview:self.addImageButton];
//    }
//}

/*
-(void)setpics:(NSArray *)pics{
    for (int i = 0; i < pics.count ; i++) {
        int d1 = i % 3;
        int d2 = i / 3;
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13*(d1+1) + 110*d1 ), ScreenX375(16*(d2-1)+110*d2 + 430), ScreenX375(110), ScreenX375(110))];
        UIImage *img = [UIImage imageWithData:[pics objectAtIndex:i]];
            image.image = img;
            [_mainView addSubview: image];
    }
    
    
    long d3 = (pics.count ) % 3;
    long d4 = (pics.count ) / 3;
    
    CGRect frame = _selectPhoto.frame;
    frame.origin.x = 13*(d3+1) + 110*d3;
    frame.origin.y = 16*(d4-1)+110*d4 + 430;
    _selectPhoto.frame = frame;
}
*/
-(void)click{
    NSLog(@"clicked");
}

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"请尽可能描述您的需求(包装材质、印刷工艺、尺寸、用途)"]) {
        textView.textColor = [UIColor blackColor];
        textView.text = @"";
    }
}

//-(void)setNumofname{
//    if(_productnamevalue.text.length <= 10){
////        NSString *num = [[NSString alloc] initWithFormat:@"%lu/10",_productnamevalue.text.length];
////        _numofname.text = num;
//    }else{
//        NSString *num = [[NSString alloc] initWithFormat:@"%@",_productnamevalue.text];
//        NSString *result = [[NSString alloc] init];
//        result = [num substringToIndex:10];
//        _productnamevalue.text = result;
//        
//        [HttpManager showNoteMsg:@"商品名称不能超过十个字"];
//    }
//}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length < 1) {
        textView.textColor = REXADECIMALCOLOR(@"#999999");
        textView.text = @"请尽可能描述您的需求(包装材质、印刷工艺、尺寸、用途)";
    }
}

- (void)btnDidClick:(UIButton *)button {
    if (button == self.selectYesButton) {
        self.selectYesButton.selected = YES;
        self.selectNoButton.selected = NO;
        self.yesOrNoType = YesOrNoType_Yes;
        self.selectYesButton.layer.borderColor = ThemeColor.CGColor;
        self.selectNoButton.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
    }else {
        self.selectYesButton.selected = NO;
        self.selectNoButton.selected = YES;
        self.yesOrNoType = YesOrNoType_NO;
        self.selectYesButton.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
        self.selectNoButton.layer.borderColor = ThemeColor.CGColor;
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return NO;
}

-(void)releasefirstResponder{
    [_productnamevalue resignFirstResponder];
    [_demandsvalue resignFirstResponder];
    [_namevalue resignFirstResponder];
    [_phonevalue resignFirstResponder];
}

@end
